package ids

import (
	"fmt"
	"strconv"
	"strings"
	errs "tacitus/library/error"
)

func ToString(ids []int64) string {
	ps := make([]string, 0)
	for _, id := range ids {
		ps = append(ps, fmt.Sprintf("%d", id))
	}
	return strings.Join(ps, ",")
}

func FromString(ids string) []int64 {
	ps := strings.Split(ids, ",")
	res := make([]int64, 0)
	for _, p := range ps {
		if id, err := strconv.ParseInt(strings.TrimSpace(p), 0, 0); err == nil {
			res = append(res, id)
		}
	}
	return res
}

func Map(ids []int64) map[int64]int {
	m := make(map[int64]int)
	for index, id := range ids {
		m[id] = index
	}
	return m
}

func AppendItem(ids *string, id int64) error {
	s := FromString(*ids)
	for _, _id := range s {
		if _id == id {
			return errs.Called("请不要添加重复项")
		}
	}
	*ids = ToString(append(s, id))
	return nil
}

func Append(ids *string, ns []int64) error {
	s := FromString(*ids)
	for _, nid := range ns {
		flag := true
		for _, _id := range s {
			if _id == nid {
				flag = false
			}
		}
		if flag {
			s = append(s, nid)
		}
	}
	*ids = ToString(s)
	return nil
}

func RemoveItem(ids *string, id int64) error {
	s := FromString(*ids)
	index := -1
	for i, _id := range s {
		if _id == id {
			index = i
			break
		}
	}
	if index == -1 {
		return errs.Called("要移除的项不存在")
	}
	*ids = ToString(append(s[:index], s[index+1:]...))
	return nil
}

// 按照指定的顺序将id重新排序
// 如果sort中存在ids中不存在的id，则丢弃，反之，则保留在末尾
func SortItem(ids *string, sort []int64) error {
	o := FromString(*ids)
	n := make([]int64, len(sort))
	m := Map(sort)
	for _, id := range o {
		if index, ok := m[id]; ok {
			n[index] = id
		} else {
			n = append(n, id)
		}
	}
	*ids = ToString(n)
	return nil
}


